class_name UnitFlySummon
extends UnitBase

# summon
var countdown_timer: float = 0
var summon_targets: Array[UnitBase] = []
@export var born_unit_data: UnitBaseData


func pick_new_wander_target():
	# 在矩形范围内随机目标点
	var x_offset = randf_range(-wander_width/2, wander_width/2)
	var y_offset = randf_range(-wander_height/2, wander_height/2)
	target_pos = home_position + Vector2(x_offset, y_offset)
	
	# 下一次切换目标时间
	timer = randf_range(1.0, change_dir_time)
	
	
func play_wander_animation():
	animation_player.play("idle")
	

func clear_invalid_summon_target():
	for i in range(summon_targets.size() - 1, -1, -1):
		if not is_instance_valid(summon_targets[i]):
			summon_targets.remove_at(i)
	
	
func process_summon(delta: float):
	var config = unit_data.config as UnitFlySummonConfig
	
	countdown_timer -= delta
	if countdown_timer <= 0:
		clear_invalid_summon_target()
		if summon_targets.size() < config.summon_max_count:
			summon_target()
		countdown_timer = config.summon_interval	
		

func summon_target():
	var unit_data = born_unit_data.duplicate(true) as UnitBaseData
	unit_data.home_position = global_position
	unit_data.pos = global_position
	unit_data.is_enemy = self.is_enemy
	
	level.level_data.units_data.append(unit_data)
	var unit_inst = level.create_unit_by_unit_data(unit_data) 
	summon_targets.append(unit_inst)
	
	
